package utils

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/linclaus/stock/pkg/model"
)

var STOCK_HOST string

func GenerateStrategy(argss [][]string) model.Strategy {
	s := model.Strategy{}
	ses := []*model.StockExpression{}

	for _, args := range argss {
		se := model.StockExpression{}
		se.CompareString = args[0]
		se.MonitorArgs = args[1 : len(args)-1]
		se.MonitorType = args[len(args)-1]
		ses = append(ses, &se)
	}
	s.StockExpressions = ses
	return s
}

func PostStrategy(strategy model.Strategy) error {
	s, err := json.Marshal(strategy)
	if err != nil {
		return err
	}

	fmt.Printf("Post Create strategy: %s\n", string(s))
	resp, err := http.Post(STOCK_HOST+"/strategy", "application/json", strings.NewReader(string(s)))
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("responseBody: %s\n", string(body))
	if resp.StatusCode != 200 {
		return errors.New("Failed")
	}
	return err
}

func DeleteStrategy(strategy model.Strategy) error {
	s, err := json.Marshal(strategy)
	if err != nil {
		return err
	}

	payload := strings.NewReader(string(s))
	fmt.Printf("Delete strategy: %s\n", string(s))

	req, _ := http.NewRequest("DELETE", STOCK_HOST+"/strategy", payload)

	req.Header.Add("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("responseBody: %s\n", string(body))
	if resp.StatusCode != 200 {
		return errors.New("Failed")
	}
	return err
}

func ParseStrategyIdToUserString(sid, stockName string) string {
	sids := strings.Split(sid, "|")
	res := []string{}
	for _, is := range sids {
		args := strings.Split(is, "_")
		tp := args[len(args)-1]
		switch tp {
		case "type001":
			res = append(res, fmt.Sprintf("%s: 当前价格%s%s", stockName, args[1], args[2]))
		case "type002":
			res = append(res, fmt.Sprintf("%s: 日涨跌幅%s%s", stockName, args[1], args[2]+"%"))
		case "type003":
			v := strings.Split(args[2], "-")
			res = append(res, fmt.Sprintf("%s: 最近%s内涨了%s", stockName, v[0], v[1]+"%"))
		case "type004":
			v := strings.Split(args[2], "-")
			res = append(res, fmt.Sprintf("%s: 最近%s内跌了%s", stockName, v[0], v[1]+"%"))
		}
	}
	return strings.Join(res, "，并且")
}
